using System;
using System.IO;
using UnityEngine;

namespace Plugins.Editor.processors
{
    public class EtsBuildProcessor : CommonPluginBuildProcessor
    {
        private const string Tuanjie110VersionCode = "2022.3.2t8";

        private const string Tuanjie110WorkHandlerFileName = "/TuanjieMainWorkerHandler.ets";

        private const string Tuanjie111WorkHandlerFileName = "/TuanjieMainWorkerHandler_1_1_1.ets";

        protected override void DoRecordFile(string path)
        {
            ModifyEtsFiles(path);
        }

        private void ModifyEtsFiles(string path)
        {
            string newUtilPath = path + OhPrePath + "/GlobalThisUtil.ts";
            string oldUtilPath = path + "/entry/src/main/ets/common/GlobalThisUtil.ts";
            File.Replace(newUtilPath, oldUtilPath, null);

            string newWorkerPath = path + OhPrePath + "/TuanjieMainWorkerHandler.ets";
            string oldWorkerPath = path + "/entry/src/main/ets/workers/" + "TuanjieMainWorkerHandler.ts";
            if (string.Compare(Application.unityVersion, Tuanjie110VersionCode, StringComparison.Ordinal) > 0)
            {
                newWorkerPath = path + OhPrePath + Tuanjie111WorkHandlerFileName;
                FileOperator.DeleteFile(path + OhPrePath + Tuanjie110WorkHandlerFileName);
            }
            else
            {
                FileOperator.DeleteFile(path + OhPrePath + Tuanjie111WorkHandlerFileName);
            }

            File.Replace(newWorkerPath, oldWorkerPath, null);
            FileOperator.ChangeFileExtension(oldWorkerPath, "ets");
            ModifyJsRegisterFile(path);

            string workerHandlerFilePath = path + "/entry/src/main/ets/workers/TuanjieMainWorker.ts";
            FileOperator workerHandlerFileOperator = new FileOperator(workerHandlerFilePath);
            workerHandlerFileOperator.ReplaceString(
                "this.threadWorker = new worker.ThreadWorker(\"entry/ets/workers/TuanjieMainWorkerHandler.ts\");",
                "    this.threadWorker = new worker.ThreadWorker(\"entry/ets/workers/TuanjieMainWorkerHandler.ets\");");
        }

        private void ModifyJsRegisterFile(string path)
        {
            string jsRegisterFilePath = path + "/entry/src/main/ets/common/TuanjieJSScriptRegister.ts";
            FileOperator foJSRegister = new FileOperator(jsRegisterFilePath);
            foJSRegister.ReplaceString("function register(tuanjieJSClasses, functionName) {",
                "function register(tuanjieJSClasses: Record<string, Object>, functionName: Function) {");
            foJSRegister.ReplaceString("var exportObj = functionName();",
                "    let exportObj: Record<string, Object> = functionName();");
            foJSRegister.ReplaceString("var tuanjieJSClasses = {};",
                "    let tuanjieJSClasses: Record<string, Object> = {};");

            FileOperator.ChangeFileExtension(jsRegisterFilePath, ".ets");
        }
    }
}